package com.nullpointer.xchat.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RejectedExecutionException;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.nullpointer.xchat.object.UserInfo;
import com.nullpointer.xchat.object.UserInfo.GenderType;
import com.quickblox.core.QBEntityCallbackImpl;
import com.quickblox.core.request.QBRequestGetBuilder;
import com.quickblox.core.request.QBRequestUpdateBuilder;
import com.quickblox.customobjects.QBCustomObjects;
import com.quickblox.customobjects.model.QBCustomObject;
import com.quickblox.customobjects.model.QBPermissions;
import com.quickblox.customobjects.model.QBPermissionsLevel;

public class Utils {

	public static void hideKeyboard(Context context, EditText editText) {
		InputMethodManager imm = (InputMethodManager) context
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
	}

	public static void showKeyboard(Context context, EditText editText) {
		InputMethodManager imm = (InputMethodManager) context
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
	}

	public static boolean isConnectingToInternet(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null)
				for (int i = 0; i < info.length; i++)
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}

		}
		return false;
	}

	@SuppressLint("NewApi")
	public static <T> void execute(AsyncTask<T, ?, ?> asyncTask, T... params) {
		try {
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
				asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
						params);
			} else {
				asyncTask.execute(params);
			}
		} catch (RejectedExecutionException e) {
			e.printStackTrace();
		}

	}

	private static HttpClient client = null;

	public static HttpClient getClient() {
		if (client == null) {
			HttpParams params = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(params, 10000);
			client = new DefaultHttpClient(params);
		}
		return client;
	}

	@SuppressLint("NewApi")
	public static void copyTextToClipboard(Context context, String content) {
		int sdk = android.os.Build.VERSION.SDK_INT;
		if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
			android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
					.getSystemService(Context.CLIPBOARD_SERVICE);
			clipboard.setText(content);
		} else {
			android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context
					.getSystemService(Context.CLIPBOARD_SERVICE);
			android.content.ClipData clip = android.content.ClipData
					.newPlainText("message", content);
			clipboard.setPrimaryClip(clip);
		}
	}

	public static UserInfo getUserInfoFromQBWebsite(String website) {
		String info = website.replace("http://", "");
		UserInfo user;
		try {
			user = UserInfo.fromJsonToUserInfo(info);
		} catch (Exception e) {
			user = new UserInfo();
			user.setGender(GenderType.FEMALE);
			user.setStatus("Hi! I'm Female");
		}

		return user;
	}

	public static void reportUser(final Integer userID) {
		QBRequestGetBuilder requestBuilder = new QBRequestGetBuilder();
		requestBuilder.setPagesLimit(1);
		requestBuilder.eq(Common.ReportObject.USER_ID_FIELD, userID);

		QBCustomObjects.getObjects(Common.ReportObject.REPORT_CLASS,
				requestBuilder,
				new QBEntityCallbackImpl<ArrayList<QBCustomObject>>() {

					@Override
					public void onSuccess(
							ArrayList<QBCustomObject> customObjects,
							Bundle params) {
						KiraGameLog.d(">>> custom objects: " + customObjects);
						if (customObjects.size() == 0) {
							QBCustomObject newRecord = new QBCustomObject(
									Common.ReportObject.REPORT_CLASS);
							newRecord.put(Common.ReportObject.USER_ID_FIELD,
									userID);
							newRecord.put(Common.ReportObject.NUM_FIELD, 1);
							QBPermissions permissions = new QBPermissions();
							permissions
									.setDeletePermission(QBPermissionsLevel.OPEN);
							permissions
									.setReadPermission(QBPermissionsLevel.OPEN);
							permissions
									.setUpdatePermission(QBPermissionsLevel.OPEN);
							newRecord.setPermission(permissions);
							QBCustomObjects.createObject(newRecord,
									new QBEntityCallbackImpl<QBCustomObject>() {
										@Override
										public void onSuccess(
												QBCustomObject object,
												Bundle params) {
											KiraGameLog
													.d(">>> created object: "
															+ object);
										}

										@Override
										public void onError(List<String> errors) {
											KiraGameLog
													.d("create getReportUser error "
															+ errors);
										}
									});
						} else {
							QBCustomObject object = customObjects.get(0);
							int num = Integer.parseInt(object.getFields()
									.get(Common.ReportObject.NUM_FIELD)
									.toString());
							object.put(Common.ReportObject.NUM_FIELD, num + 1);
							QBCustomObjects.updateObject(object,
									(QBRequestUpdateBuilder) null,
									new QBEntityCallbackImpl<QBCustomObject>() {
										@Override
										public void onSuccess(
												QBCustomObject object,
												Bundle params) {
											KiraGameLog
													.d(">>> updated record: : "
															+ object.toString());
										}

										@Override
										public void onError(List<String> errors) {
											KiraGameLog
													.d("update getReportUser error "
															+ errors);
										}
									});
						}

					}

					@Override
					public void onError(List<String> errors) {
						KiraGameLog.d("getReportUser error " + errors);
					}
				});

	}

	public static boolean checkBadword(String input) {
		input = input.toLowerCase();
		for (String word : Common.badWord) {
			if (input.contains(word)) {
				return true;
			}
		}
		return false;
	}
}
